tm.mapSearch =
{
	data: null,
	geocoder: null,
	mapCenter: null,
	mapDefZoom: 4,
	addressMarker: [],
	gmarkers: [],
	attrmarkers: [],
	map: null,
	cDelta: 150,
	infoActive: false,
	
	progressBar: null,
	points: [],
	dataHotels: [],
	maxNum: 0,
	num: 0,
	hotelsToSearch: [],

	init: function()
	{
		if ($('#gmap').length > 0) {
			if (GBrowserIsCompatible()) {
				tm.mapSearch.map = new google.maps.Map2(document.getElementById("gmap"));
				tm.mapSearch.mapCenter = new google.maps.LatLng(47.87214396888731, 25.83984375);
				tm.mapSearch.map.setCenter(tm.mapSearch.mapCenter, tm.mapSearch.mapDefZoom);
				
				GEvent.addListener(tm.mapSearch.map, "moveend", tm.mapSearch.moveendEvent);
				tm.mapSearch.map.enableScrollWheelZoom();
				//tm.mapSearch.map.enableGoogleBar();
				//tm.mapSearch.map.setUIToDefault();
				tm.mapSearch.map.addControl(new GLargeMapControl());
				tm.mapSearch.map.addControl(new GMapTypeControl());
				
				tm.mapSearch.geocoder = new GClientGeocoder();
			}
			
			$('#m-countries-wrapper .m-countries-item a').click(tm.mapSearch.countryClick);
	
			$('#lnk-search').click(tm.mapSearch.lnkSearchFn);
			$('#lnk-maps').click(tm.mapSearch.lnkMapsFn);
			$('#m-countries .controls a.toright').click(tm.mapSearch.torightClick);
			$('#m-countries .controls a.toleft').click(tm.mapSearch.toleftClick);
			
			/*
			var attracts = $('#attractions-categories');
			$('#show_attractions a').click(function() {
				if (attracts.is(':hidden')) {
					attracts.show();
					$(this).css('backgroundPosition', '100% -30px');
				} else {
					attracts.hide();
					$(this).css('backgroundPosition', '100% 1px');
				}
			});
			*/
			
			$('#request-input-holder form').submit(tm.mapSearch.globalSearchFormSubmit);
			
			$('body').unload(GUnload);
		}
	},
	moveendEvent: function(event)
	{
		if (tm.mapSearch.geocoder) {
			var bounds = tm.mapSearch.map.getBounds();
			var southWest = bounds.getSouthWest();
			var northEast = bounds.getNorthEast();
			var mapZoom = tm.mapSearch.map.getZoom();
			
			var sendData = {southWestLat: southWest['Ye'], southWestLon: southWest['Va'], northEastLat: northEast['Ye'], northEastLon: northEast['Va'], zoom: mapZoom};
			$.ajax({
				url: '/a_search/hotelgeo.getHotelsByCoordinates',
				data: sendData,
				dataType: "json",
				type: "POST",
				success: function(data) {
					tm.mapSearch.removeMapLoading();
					if (data.status == 'success') {
						tm.mapSearch.dataHotels = data.data.hotels;
						tm.mapSearch.maxNum = tm.mapSearch.dataHotels.length;
						if (tm.mapSearch.maxNum > 0) {
							tm.mapSearch.removeMarkers(tm.mapSearch.gmarkers);
							if (tm.mapSearch.progressBar) tm.mapSearch.progressBar.remove();
							tm.mapSearch.num = 0;
							window.clearTimeout();
							tm.mapSearch.progressBar = new ProgressbarControl(tm.mapSearch.map, {loadstring: 'Загрузка...', width:150});
							tm.mapSearch.progressBar.start(tm.mapSearch.maxNum);
							tm.mapSearch.createMarker(tm.mapSearch.num);
						}
					} else {
						alert('Search error. Server does\'nt response.');
					}
				},
				error: function() {
					tm.mapSearch.removeMapLoading();
					alert('Search error. Server is down.');
				}
			});
		}
	},
	lnkSearchFn: function()
	{
		var $this = $(this);
		if (!$this.hasClass('selected')) {
			$('#map-search').hide();
			$('#hotel_search').show();
			$('#cnt-top #char').show();
			$('#lnk-maps').removeClass('selected');
			$this.addClass('selected');
		}
	},
	lnkMapsFn: function()
	{
		var $this = $(this);
		if (!$this.hasClass('selected')) {
			$('#hotel_search').hide();
			$('#cnt-top #char').hide();
			$('#map-search').show();
			$('#lnk-search').removeClass('selected');
			$this.addClass('selected');
			$('#global_search').focus().css('borderWidth', '2px');
		}
		
		tm.mapSearch.map.checkResize();
		tm.mapSearch.map.setCenter(tm.mapSearch.mapCenter, tm.mapSearch.mapDefZoom);
	},
	countryClick: function()
	{
		$('#global_search').val($(this).attr('name'));
		tm.mapSearch.globalSearchFormSubmit();
	},
	createMarker: function()
	{
		if (tm.mapSearch.num >= 0 && tm.mapSearch.dataHotels[tm.mapSearch.num] != undefined) {
			
			tm.mapSearch.points[tm.mapSearch.num] = new GLatLng(tm.mapSearch.dataHotels[tm.mapSearch.num].latitude, tm.mapSearch.dataHotels[tm.mapSearch.num].longitude);
			tm.mapSearch.gmarkers[tm.mapSearch.num] = new GMarker(tm.mapSearch.points[tm.mapSearch.num]);
			tm.mapSearch.map.addOverlay(tm.mapSearch.gmarkers[tm.mapSearch.num]);
			var iHotel = tm.mapSearch.dataHotels[tm.mapSearch.num];
			var metadata = "{countryCode: '" + iHotel.countryCode + "', countryTranslation: '" + iHotel.countryTranslation + "', cityId: '" + iHotel.cityId + "', cityTranslation: '" + iHotel.cityTranslation + "', name: '" + iHotel.name + "'}";
			var iText = '<div class="info-text"><p class="location"><span class="country" title="' + iHotel.countryCode + '">' + iHotel.countryTranslation + '</span>, <span class="city" title="' + iHotel.cityId + '">' + iHotel.cityTranslation + '</span></p><p class="name">' + iHotel.name + '</p><span class="control"><a class="use-in-search ' + metadata + '" href="javascript:void(0)">Использовать в поиске</a></span></div>';

			var infoWin = tm.mapSearch.map.getInfoWindow();
			tm.mapSearch.gmarkers[tm.mapSearch.num].content = iText;
			tm.mapSearch.markerClickEvent(tm.mapSearch.gmarkers[tm.mapSearch.num], infoWin, iHotel);
			tm.mapSearch.map.addOverlay(tm.mapSearch.gmarkers[tm.mapSearch.num]);
			tm.mapSearch.markerShowInfo(tm.mapSearch.gmarkers[tm.mapSearch.num]);
			
			if (tm.mapSearch.num < tm.mapSearch.maxNum - 1) {
				setTimeout('tm.mapSearch.createMarker(tm.mapSearch.num++)', 0);
				tm.mapSearch.progressBar.updateLoader(1);
			} else {
				tm.mapSearch.progressBar.remove();
				tm.mapSearch.num = 0;
			}
		} else {
			window.clearTimeout();
		}
	},
	showAddress: function(global, bool)
	{
		if (tm.mapSearch.geocoder) {
			//tm.mapSearch.removeMarkers(tm.mapSearch.gmarkers);
			var bounds = tm.mapSearch.map.getBounds();
			var southWest = bounds.getSouthWest();
			var northEast = bounds.getNorthEast();
			var mapZoom = tm.mapSearch.map.getZoom();
			
			var sendData = {southWestLat: southWest['Ye'], southWestLon: southWest['Va'], northEastLat: northEast['Ye'], northEastLon: northEast['Va'], zoom: mapZoom};
			if (bool) {
				sendData.search = global;
			}
			$.ajax({
				//url: '/a_ajax/Geoname.getCoords',
				url: '/a_search/hotelgeo.gethotels',
				data: sendData,
				dataType: "json",
				type: "POST",
				success: function(data) {
					if (data.status == 'success') {
						tm.mapSearch.dataHotels = data.data.hotels;
						tm.mapSearch.maxNum = tm.mapSearch.dataHotels.length;
						if (data.data.country) {
							var locationCountry = data.data.country;
							var geoCoder_ = new GClientGeocoder();
							tm.mapSearch.removeMarkers(tm.mapSearch.gmarkers);
							geoCoder_.getLatLng(locationCountry, function(point) {
								if (point) {
									tm.mapSearch.map.panTo(point);
									if (tm.mapSearch.progressBar) tm.mapSearch.progressBar.remove();
									tm.mapSearch.num = 0;
									window.clearTimeout();
									if (data.data.hotels.length > 0) {
										tm.mapSearch.progressBar = new ProgressbarControl(tm.mapSearch.map, {loadstring: 'Загрузка...', width:150});
										tm.mapSearch.progressBar.start(tm.mapSearch.maxNum);

										tm.mapSearch.createMarker(tm.mapSearch.num);
									}
								}
							});
						}
						if (data.data.autocomplete.length > 0) {
							tm.mapSearch.bindAutocomlete(data);
						}
						//$('#show_attractions').show();
						//tm.mapSearch.attractionsEvents(data.attractions);
						
					} else {
						alert('Search error. Server does\'nt response.');
					}
					tm.mapSearch.removeMapLoading();
				},
				error: function() {
					tm.mapSearch.removeMapLoading();
					alert('Search error. Server is down.');
				}
			});
		}
	},
	removeMarkers: function(markers) {
		if (markers) {
			for (var m = 0; m < markers.length; m++) {
				tm.mapSearch.map.removeOverlay(markers[m]);
			}
		}
	},
	removeAllMarkers: function()
	{
		var allMarkers = [];
		if (tm.mapSearch.gmarkers) {
			allMarkers = allMarkers.concat(tm.mapSearch.gmarkers);
		}
		if (tm.mapSearch.attrmarkers) {
			allMarkers = allMarkers.concat(tm.mapSearch.attrmarkers);
		}
		if (allMarkers.length > 0) {
			for (var m = 0; m < allMarkers.length; m++) {
				tm.mapSearch.map.removeOverlay(allMarkers[m]);
			}
		}
	},
	attractionsEvents: function(data)
	{
		$('#attractions-categories li input[type="checkbox"]:checked').removeAttr('checked').next('a.tm-checkbox').find('img').removeClass('checked');
		$('#attractions-categories li input[type="checkbox"]').bind('click', {attractions: data, aType: this.value}, tm.mapSearch.attractionsClick);
	},
	attractionsClick: function(event)
	{
		var data = event.data;
		tm.mapSearch.removeMarkers(tm.mapSearch.attrmarkers);
		if (data.attractions != 'undefined') {
			var elm = event.target;
			if (elm.checked) {
				tm.mapSearch.showAttractions(elm, data.attractions, data.aType);
			} else {
				tm.mapSearch.hideAttractions(elm, data.attractions);
			}
		}
	},
	showAttractions: function(elm, data, aType)
	{
		var points = [];
		for (var j = 0; j < data.length; j++) {
//			if () {
				points[j] = new GLatLng(data[j].lat, data[j].lon);
				var myIcon = new GIcon(G_DEFAULT_ICON);
				myIcon.image = "http://tmua.serega.dev.mrise.ru/i/chief-base.png";
				var markerOptions = {icon: myIcon};
				
				//tm.mapSearch.attrmarkers[j].content = 
				
				tm.mapSearch.attrmarkers[j] = new GMarker(points[j], markerOptions);
				tm.mapSearch.map.addOverlay(tm.mapSearch.attrmarkers[j]);
				//tm.mapSearch.markerShowInfo(tm.mapSearch.attrmarkers[j]);
//			}
		}
	},
	hideAttractions: function()
	{
		tm.mapSearch.removeMarkers(tm.mapSearch.attrmarkers);
	},
	showInfoWins: function(data)
	{
		var points = [];
		var gmarkers = [];
		var infoWin = tm.mapSearch.map.getInfoWindow();
		for(var i = 0; i < data.hotels.length; i++) {
			points[i] = new GLatLng(data.hotels[i].latitude, data.hotels[i].longitude);
			tm.mapSearch.gmarkers[i] = new GMarker(points[i]);
			
			var iHotel = tm.mapSearch.dataHotels[tm.mapSearch.num];
			var metedata = {countryCode: iHotel.countryCode, countryTranslation: iHotel.countryTranslation, cityId: iHotel.cityId, cityTranslation: iHotel.cityTranslation, name: iHotel.name};
			var iText = '<div class="info-text"><p class="location"><span class="country" title="' + iHotel.countryCode + '">' + iHotel.countryTranslation + '</span>, <span class="city" title="' + iHotel.cityId + '">' + iHotel.cityTranslation + '</span></p><p class="name">' + iHotel.name + '</p><span class="control"><a class="use-in-search ' + metedata + '" href="javascript:void(0)">Использовать в поиске</a></span></div>';
			tm.mapSearch.gmarkers[i].content = iText;
			tm.mapSearch.markerClickEvent(tm.mapSearch.gmarkers[i], infoWin, iHotel);
			tm.mapSearch.map.addOverlay(tm.mapSearch.gmarkers[i]);
			tm.mapSearch.markerShowInfo(tm.mapSearch.gmarkers[i]);
		}
		tm.mapSearch.map.setCenter(new GLatLng(data.hotels[0].latitude, data.hotels[0].longitude));
		//var infoWin = tm.mapSearch.map.getInfoWindow();
	},
	markerClickEvent: function(marker, infoWin, iHotel)
	{
		GEvent.addListener(marker, "mouseover", function() {
			if (!tm.mapSearch.infoActive) {
				marker.openInfoWindowHtml(marker.content);
				$('div.info-text a.use-in-search').one('click', tm.mapSearch.useInSearchClick);
			}
		});
		GEvent.addListener(marker, "click", function() {
			$('div.info-text a.use-in-search').unbind('click', tm.mapSearch.useInSearchClick);
			tm.mapSearch.infoActive = true;
			marker.openInfoWindowHtml(marker.content);
			$('div.info-text a.use-in-search').bind('click', tm.mapSearch.useInSearchClick);
		});
		GEvent.addListener(infoWin, "closeclick", function() {
			tm.mapSearch.infoActive = false;
		});/*
		GEvent.addListener(tm.mapSearch.map, "infowindowbeforeclose", function() {
			tm.mapSearch.infoActive = false;
		});*/
		return marker;
	},
	markerShowInfo: function(marker)
	{
		$('div.info-text a.use-in-search').unbind('click', tm.mapSearch.useInSearchClick);
		marker.openInfoWindowHtml(marker.content);
		$('div.info-text a.use-in-search').bind('click', tm.mapSearch.useInSearchClick);
		return marker;
	},
	useInSearchClick: function(event)
	{
		var iHotel = $(event.target).metadata();
		var oHotel = {name: iHotel.name, countryCode: iHotel.countryCode, cityId: iHotel.cityId};
		var validArray = true;
		for (var j = 0; j < tm.mapSearch.hotelsToSearch.length; j++) {
			if (tm.mapSearch.hotelsToSearch[j].name == iHotel.name && tm.mapSearch.hotelsToSearch[j].countryCode == iHotel.countryCode && tm.mapSearch.hotelsToSearch[j].cityId == iHotel.cityId)
				validArray = false;
		}
		if (validArray) tm.mapSearch.hotelsToSearch.push(oHotel);
		
		var continue_ = true;
		var links = $('div.right-col div.links dl');
		
		links.append('<dt><input type="radio" name="hn[]" /></dt><dd></dd>');

//		tm.mapSearch.hotelsToSearch
		
		var hotelName = $.trim($(this).parents('div.info-text').find('.name').text());
		var country = $.trim($(this).parents('div.info-text').find('.country').text());
		var city = $.trim($(this).parents('div.info-text').find('.city').text());
		var continue_ = true;
		var links = $('div.right-col div.links');
		$('div.right-col div.links span input[type="hidden"]').each(function() {
			if ($(this).val() == hotelName) {
				continue_ = false;
			}
		});
		if (continue_) {
			var span = $('<span><a class="remove-hotel" href="javascript:void(0)">x</a> <input class="inp-hotel-name" type="hidden" name="hn[]" value="' + hotelName + '" />' + hotelName + '</span>');
			links.find('strong').hide();
			links.append(span);
		}
		$('div.right-col div.links span a.remove-hotel').click(removeFromSearch);
	},
	removeFromSearch: function()
	{
		
		var $this = $(this);
		$this.parents('span').remove();
		if (links.find('span').size() == 0) {
			links.find('strong').show();
		}
	},
	torightClick:function()
	{
		var d = parseInt($('#m-countries-wrapper').css('marginLeft'));
		var $this = $(this);
		if ($('#m-countries-wrapper .m-countries-item').size() * tm.mapSearch.cDelta - tm.mapSearch.cDelta + d > 0) {
			if ($('#m-countries .controls a.toleft').hasClass('hidden')) {
				$('#m-countries .controls a.toleft').removeClass('hidden');
			}
			$('#m-countries .controls a.toright').unbind('click', tm.mapSearch.torightClick);
			$('#m-countries-wrapper').animate({marginLeft: d - tm.mapSearch.cDelta}, 300, function() {
				$('#m-countries .controls a.toright').bind('click', tm.mapSearch.torightClick);
			});
			if ($('#m-countries-wrapper .m-countries-item').size() * tm.mapSearch.cDelta + d == 2 * tm.mapSearch.cDelta) {
				$this.addClass('hidden');
			}
		}
	},
	toleftClick: function()
	{
		var d = parseInt($('#m-countries-wrapper').css('marginLeft'));
		var $this = $(this);
		if (d < 0) {
			if ($('#m-countries .controls a.toright').hasClass('hidden')) {
				$('#m-countries .controls a.toright').removeClass('hidden');
			}
			//$('#m-countries-wrapper').css('marginLeft', d + tm.mapSearch.cDelta);
			$('#m-countries .controls a.toleft').unbind('click', tm.mapSearch.toleftClick);
			$('#m-countries-wrapper').animate({marginLeft: d + tm.mapSearch.cDelta}, 300, function() {
				$('#m-countries .controls a.toleft').bind('click', tm.mapSearch.toleftClick);
			});
			if (d + tm.mapSearch.cDelta == 0) {
				$this.addClass('hidden');
			}
		}
	},
	globalSearchFormSubmit: function()
	{
		if ($('#autocomplete-container').length > 0) {
			$('#autocomplete-container').remove();
		}
		$('#show_attractions').hide();
		$('#attractions-categories li input[type="checkbox"]').unbind('click', tm.mapSearch.attractionsClick);
		if ($('#global_search').val() != '') {
			tm.mapSearch.setMapLoading();
			tm.mapSearch.showAddress($('#global_search').val(), true);
		} else {
			alert('Введите запрос поиска. Пример: "Страна, город, название отеля"');	
		}
		return false;
	},
	setMapLoading: function()
	{
		var gmap = $('#gmap');
		var loading = $('<img id="gmap-ajax-loader" src="/i/ajax-loader-transparent.gif" width="33" height="33" alt="Loading..." />');
		gmap.css('opacity', 0.5).append(loading);
		loading.css({
			left: (gmap.width() - loading.width()) / 2,
			top: (gmap.height() - loading.height()) / 2
		});
	},
	removeMapLoading: function()
	{
		$('#gmap').css('opacity', 1);
		$('#gmap-ajax-loader').remove();
	},
	bindAutocomlete: function(data)
	{
		
		var form = $('#global_search').parents('form');
		var acl = data.data.autocomplete.length;
		var aRows = '';
		for (var i = 0; i < acl; i++) {
			var this_ = data.data.autocomplete[i];
			var metadata = "{grade: '" + this_.grade + "', name: '" + this_.name + "', address: '" + this_.address.replace(/'/gi, '') + "', longitude: '" + this_.longitude + "', latitude: '" + this_.latitude + "', countryName: '" + this_.countryName + "', cityName: '" + this_.cityName + "'}";
			aRows += '<a href="javascript:void(0)" class="' + metadata + '">' + '<em>' + this_.countryName + ', ' + this_.cityName + '</em>, <b>' + this_.name + '</b></a>';
		}
		form.css('position', 'relative').append('<div id="autocomplete-container">' + aRows + '</div>');
		
		tm.mapSearch.bindAutocompleteEvents(data);
	},
	bindAutocompleteEvents: function(data)
	{
		var isHovered = false;
		$('#autocomplete-container').bind('mouseover', function() {
			isHovered = true;
		});
		$('#autocomplete-container').bind('mouseleave', function() {
			isHovered = false;
			setTimeout(function() {
				if (!isHovered) {
					tm.mapSearch.unbindAutocomlete();
				}
			}, 2000);
		});
		$('#autocomplete-container a').bind('click', {dataContainer: data}, tm.mapSearch.autocompleteClick);
	},
	autocompleteClick: function(event)
	{
		var elm = $(this);
		var dataContainer = event.data.dataContainer;
		var serachString = elm.metadata().countryName + ', ' + elm.metadata().cityName + ', ' + elm.metadata().name;
		$('#global_search').val(serachString);
		tm.mapSearch.showHotel(elm.metadata());
		tm.mapSearch.unbindAutocomlete();
	},
	showHotel: function(data)
	{
		var point = new GLatLng(data.latitude, data.longitude);
		var infoWin = tm.mapSearch.map.getInfoWindow();
		var iText = '<div class="info-text"><p class="name">' + data.name + '</p><span class="control"> <a class="use-in-search" href="javascript:void(0)">Использовать при поиске</a></span></div>';
		tm.mapSearch.map.setCenter(point);
		var hotelMarker = new GMarker(point);
		hotelMarker.content = iText;
		tm.mapSearch.map.addOverlay(hotelMarker);
		tm.mapSearch.markerClickEvent(hotelMarker, infoWin);
	},
	unbindAutocomlete: function()
	{
		$('#autocomplete-container').remove();
	}
};

$(tm.mapSearch.init);